using Rabbit3.Api.Common;
using Rabbit3.Api.Models;
using Rabbit3.Api.Services;
using Rabbit3.Api.MyProfiles;
using Rabbit3.Api.Middleware;
using AutoMapper;
using SqlSugar;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// 获取连接字符串，注册 SqlSugar和MySQL的
var connStr = builder.Configuration.GetConnectionString("MySqlConnection"); // 从配置文件中获取MySQL连接字符串

// 简化的数据库连接配置
var connectionConfig = new ConnectionConfig
{
    ConnectionString = connStr,
    DbType = DbType.MySql,
    IsAutoCloseConnection = true,
    InitKeyType = InitKeyType.Attribute
};

builder.Services.AddSingleton<ISqlSugarClient>(new SqlSugarClient(connectionConfig));

// 注册内存缓存
builder.Services.AddMemoryCache();

// 注册AutoMapper - 使用原始配置确保兼容性
builder.Services.AddAutoMapper(typeof(TraceabilityProfile));

// 注册服务 - 使用原始版本确保稳定性
builder.Services.AddScoped<ITraceabilityService, TraceabilityService>();
builder.Services.AddScoped<IFarmingService, FarmingService>();
builder.Services.AddScoped<IProcessingService, ProcessingService>();
builder.Services.AddScoped<ISlaughterService, SlaughterService>();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(a => // 配置Swagger文档
{
	var path = AppDomain.CurrentDomain.BaseDirectory + "Rabbit3.Api.xml"; // 获取XML文档文件路径
	a.IncludeXmlComments(path, true); // 包含XML注释到Swagger文档
});

var app = builder.Build();
app.UseCors(a=>a.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());

// 添加性能监控中间件
app.UsePerformanceMonitoring();

// 使用 CodeFirst 确保首次运行自动创建数据库和表结构/更新表
var db = app.Services.GetRequiredService<ISqlSugarClient>();
db.CodeFirst.InitTables( // 使用CodeFirst模式初始化数据表
	typeof(TraceabilityInfo),
	typeof(FarmingInfo),
	typeof(ImmunityInfo),
	typeof(EnterpriseInfo),
	typeof(ProcessingInfo),
	typeof(SlaughterInfo),
	typeof(SupplierInfo)
);

// 创建数据库索引以提高性能
DatabaseOptimization.CreateIndexes(db);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();